package com.ruoyi.web.controller.common;

import com.ruoyi.common.core.domain.AjaxResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @description:WxPortalController
 * @author: caoes
 * create:2023/6/28 14:16
 **/
@RestController
@RequestMapping("/wechat/{appId}")
public class WxPortalController {

    private static final Logger logger = LoggerFactory.getLogger(WxPortalController.class);

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WxMpMessageRouter wxMpMessageRouter;

    @GetMapping(produces = "text/plain;charset=utf-8")
    public String auth(@PathVariable String appId,
                       @RequestParam(name = "signature",required = true) String signature,
                       @RequestParam(name = "timestamp",required = true) String timestamp,
                       @RequestParam(name = "nonce",required = true) String nonce,
                       @RequestParam(name = "echostr",required = true) String echostr) {

        logger.info("接收到来自微信服务器的认证消息, signature:{}, timestamp:{}, nonce:{} ,echostr:{}",signature,timestamp,nonce,echostr);
        if (!this.wxMpService.switchover(appId)) {
            throw new IllegalArgumentException("非法参数");
        }
        if (wxMpService.checkSignature(timestamp,nonce,signature)) {
            return echostr;
        }
        return "非法请求";
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable String appId,
                       @RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openId,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {

        logger.info("接收微信请求：[openId={}, signature={}, encType={}, msgSignature={}, timestamp={}, nonce={], requestBody={} ", openId, signature, encType, msgSignature, timestamp, nonce, requestBody);
        if (!this.wxMpService.switchover(appId)) {
            throw new IllegalArgumentException("非法参数");
        }
        if (!wxMpService.checkSignature(timestamp,nonce,signature)) {
            throw new IllegalArgumentException("非法参数");
        }
        String out = null;
        if (encType == null) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxMpService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            logger.debug("消息解密后内容为：{} ", inMessage.toString());
            WxMpXmlOutMessage outMessage = this.route(inMessage);
            if (outMessage == null) {
                return "";
            }

            out = outMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
        }

        logger.debug("组装回复信息：{}", out);
        return out;
    }

    private WxMpXmlOutMessage route(WxMpXmlMessage message) {
        try {
            return this.wxMpMessageRouter.route(message);
        } catch (Exception e) {
            logger.error("路由消息时出现异常！", e);
        }

        return null;
    }

    @GetMapping( value = "/getQrCode")
    public AjaxResult getQrCode(@PathVariable String appId) throws WxErrorException {
        if (!this.wxMpService.switchover(appId)) {
            throw new IllegalArgumentException("非法参数");
        }
        WxMpQrCodeTicket wxMpQrCodeTicket = wxMpService.getQrcodeService().qrCodeCreateTmpTicket(123, 600);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("data", wxMpQrCodeTicket);
        return ajax;
    }
}
